<template>
	<view class="content">
		<van-nav-bar title="填写售后卡" left-text="返回" left-arrow @click-left="onClickLeft" />

		<van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
			客户信息填写
		</van-divider>
		<view>
			<van-form>
				<van-cell-group inset>
					<van-cell center title="产品名称" value-class="balck_flex_3" :value="product_title" />
					<van-cell center title="保修时长(月)" value-class="balck_flex_3" :value="createdate||12" />
					<van-cell center title="到期时间" value-class="balck_flex_3" :value="end_data" />

					<van-field v-model="fac_name" is-link required label="安装门店" placeholder="选择安装门店"
						@click="showPicker = true" />
					<van-field v-model="realname" label="姓名" required placeholder="请输入您的姓名" />
					<!-- 通过 validator 进行函数校验 -->
					<van-field v-model="phone" label="电话" required name="phone" placeholder="请输入您的手机号" />
					<!-- 通过 validator 返回错误提示 -->

					<!-- required -->
					<van-field v-model="idCard" label="身份证" name="idCard" placeholder="请输入您的身份证号" />
					<van-field v-model="carNumber" label="车牌号" name="carNumber" placeholder="请输入您的车牌号" />
					<van-field v-model="maintenance_period" label="保养周期(月)" name="carNumber" placeholder="请输入需要保养的周期" />
					<van-popup v-model:show="showPicker" round position="bottom">
						<van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
					</van-popup>
					<van-field v-model="content" rows="1" autosize label="备注" type="textarea" placeholder="请输入留言" />

				</van-cell-group>
				<van-highlight class="highlight" :keywords="keywords" :source-string="text"
					highlight-class="custom-class" />
				<div style="margin: 16px;">
					<van-button style="font-size: 16px;" round block type="primary" native-type="submit"
						@click="comfirm()">
						提 交
					</van-button>
				</div>
			</van-form>
		</view>
	</view>
</template>

<script>
	import {
		showConfirmDialog,
		showToast,
		showSuccessToast,
		showFailToast,
		Toast
	} from 'vant';
	import wxjs from "@/utils/wxjsdk.js";
	import axios from 'axios';
	// import jweixin from '@/utils/jweixin-1.6.0.js'
	const isWechat = () => {
		return (
			String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) ===
			"micromessenger"
		);
	};
	export default {
		data() {
			return {
				content: '',
				product_code: '',
				weixinCode: '', // 微信获取的code
				link: "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEJNfmdUC9sNSseiayaDw2rYdLEcQiaZjRiaHf5rticjFwZxG2PGdxZLVHlER5yia3ZHNicoox8JruwaVy2I1WVia8b6E8S8NV26zXduUH7f9lpO5wiarw/132",
				product_status: '',
				product_status_name: '',
				product_title: '',
				createdate: '', // 保修时长
				end_time: '', // 到期时间
				maintenance_period: 6, // 保养周期
				fac_name: '', // 门店名称 ，但是这个的值是通过接口获取到的门店id
				showPicker: false, // 是否显示选择器
				fieldValue: '', // 选择器的值
				columns: [], // 选择器的列
				realname: '',
				phone: '',
				status: '',
				idCard: '',
				carNumber: '',
				text: '请确认您的基本信息是否无误',
				keywords: ['请确认您的基本信息是否无误'],
			}
		},
		onLoad() {
			this.getFactoryList();
			// 获取当前请求连接上的参数
			let url = window.location.href;
			// 截取url中的参数
			let index = url.indexOf("productCode"); //获取=的位置
			console.log('index', index);
			let str = url.substr(index + 12); //获取?之后的参数
			if (str == undefined || str == null) {
				setTimeout(() => {
					showToast("无法获取产品信息，正在返回首页");
				}, 1000);
				uni.navigateTo({
					url: '/',
				});
			}
			this.productCode = str;
			if (str) {
				// window.location.reload();
				this.getProductList(str);
			} else {
				showToast("请返回并输入序列号");
			}
		},

		methods: {
			onClickLeft() {
			     uni.navigateBack({
			       delta: 1 // 返回的页面数，1表示返回上一页，2表示返回上两页，以此类推
			     })
			   },
			getFactoryList() {
				axios.get('https://service.wulings.com/api/code/getFactoryList').then(res => {
					console.log('getFactoryListRes', res.data);
					res.data.forEach(item => {
						item.text = item.factory;
						item.value = item.id;
						this.columns.push(item);
					})
					// this.columns.push(res.data);
					console.log('columns', this.columns);
				})
			},

			// onConfirm 选择器确认事件
			onConfirm(selectedOptions) {
				console.log('selectedOptions', selectedOptions);
				this.fac_name = selectedOptions.selectedOptions[0].text;
				this.fieldValue = selectedOptions.selectedOptions[0].value;
				this.showPicker = false;
			},

			getProductStatusText(status) {
				if (status === 1) {
					this.product_status_name = '良好';
				} else if (status === 2) {
					this.product_status_name = '不良';
				}
			},

			getStatusType(product_status_name) {
				switch (product_status_name) {
					case '良好':
						return 'success';
					case '不良':
						return 'danger';
					default:
						return '';
				}
			},

			getStatusText(status) {
				switch (status) {
					case 0:
						return '未使用';
					case 1:
						return '未激活';
					case 2:
						return '已激活';
					case -1:
						return '已删除';
					case 4:
						return '已作废';
					case 5:
						return '已出库';
					case 6:
						return '已入库';
					default:
						return '未知状态';
				}
			},

			getProductList(code) {
				let productList = uni.request({
					url: "https://service.wulings.com/api/code/getCodeList",
					method: 'GET', // 请求方法，可选值包括 'GET'、'POST' 等
					data: {
						code: code
					}, // 请求参数

					success: res => {
						console.log("获取到的数据：", res.data);
						// this.ID = res.data.id;
						this.createdate = res.data.createdate || 12;
						this.link = res.data.link;
						// 到期时间 = 当前时间 + 保修时长
						// 将当前时间存储为一个新的 Date 对象
						var currentDate = new Date();
						var year = currentDate.getFullYear();
						var month = ('0' + (currentDate.getMonth() + 1)).slice(-2); // 使用两位数表示月份
						var day = ('0' + currentDate.getDate()).slice(-2); // 使用两位数表示日期

						var formattedDate = year + '-' + month + '-' + day; // 格式化为 "YYYY-MM-DD" 形式
						// 将保修时长添加到当前月份
						month = parseInt(month) + parseInt(this.createdate);
						// 如果月份大于 12，则年份加 1，月份减 12
						while (month > 12) {
							year++;
							month -= 12;
						}
						// 如果月份小于 10，则在前面添加 0
						if (month < 10) {
							month = '0' + month;
						}
						// 到期时间
						currentDate = year + '-' + month + '-' + day;
						this.end_data = currentDate
						// 将 current_date 变成十位数的时间戳
						currentDate = new Date(currentDate).getTime() / 1000;
						this.end_time = currentDate;
						this.product_code = res.data.code;
						this.product_title = res.data.product_title;
						this.createtime = res.data.createtime;
						this.bathtime = res.data.bathtime;
						this.product_status = res.data.product_status;
						this.status = res.data.status;
					},
					fail: err => {
						// 请求失败时的回调函数
						showFailToast('获取失败 ');
					}
				});
			},

			comfirm() {
				
				if (this.realname == "" || this.phone == "") {
					showToast('请完善信息后提交');
					return;
				}

				showConfirmDialog({
						message: '请确认您填写的身份信息无误。',
					})
					.then(() => {
						axios({
								method: 'post',
								url: 'https://service.wulings.com/api/code/addCodeLog',
								data: {
									"openid": uni.getStorageSync('openid'),
									"latitude": uni.getStorageSync('latitude'),
									"longitude": uni.getStorageSync('longitude'),
									"code": this.productCode,
									"phone": this.phone,
									"realname": this.realname,
									"idCard": this.idCard,
									"carNumber": this.carNumber,
									"content": this.content,
									"createdate": this.createdate, // 保修时长
									"end_time": this.end_time, // 到期时间
									"maintenance_period": this.maintenance_period, // 保养周期
									"fieldValue": this.fieldValue, // 工厂代号
									"option_type": 3, // 操作类型
								},
								headers: {
									'Content-Type': 'application/x-www-form-urlencoded'
								}
							})
							.then((res) => {
								// console.log('这次的code',this.productCode);
								console.log(res);
								if (res.data === 1) {
									showToast('提交成功');
									setTimeout(() => {
										uni.reLaunch({
											url: '/',
										});
									}, 500);
								} else {
									showToast('提交失败 ' + res.data.message);
								}
							}).catch((res) => {
								console.log('error', res);
								showToast('提交失败 ' + res.data.message);
							})
						// }

					})
					.catch(() => {
						// on cancel
						showToast("客户取消确认");
					});
			},
			// onClickLeft(){
			// 	// 回到上一级
			// 	this.$router.back();
			// }
		}
	}
</script>

<style>
	.content {
		/* background-color: #f7f8fa; */
	}

	.highlight {
		text-align: center;
		font-size: 12px;
		margin-top: 10px;
		margin-bottom: 10px;
	}

	/deep/ .custom-class {
		color: #f44;
	}

	/deep/ .van-card__thumb {
		border-radius: 10px;
		/* 设置圆角 */
		/* 其他你想要自定义的样式 */
		height: 150px;
		width: 150px;
	}

	/deep/ .van-card__title {
		/* 其他你想要自定义的样式 */
		font-size: 16px;
		width: 100%;
		height: 60px;
		line-height: 2;
		/* 居中 */
		text-align: center;
		/* 水平居中 */
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}

	/deep/ .van-card__desc {
		/* 其他你想要自定义的样式 */
		font-size: 14px;
		width: 100%;
		height: 60px;
		margin-bottom: 50px;
	}
</style>